package com.lee.sshclient;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by le on 2016/2/15.
 */
public class ShellCallback extends OutputStream {
    /*public synchronized void delete(int count) {
        super.buf = Arrays.copyOfRange(super.buf, count, super.count);
    }

    public synchronized byte[] toByteArrayAndReset() {
        byte[] buf = super.toByteArray();
        super.reset();
        return buf;
    }*/

    protected Callback callback;
    protected String charset;

    public ShellCallback(Callback callback, String charset) {
        this.callback = callback;
        this.charset = charset;
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public interface Callback {
        void execute(String response);
    }

    @Override
    public synchronized void write(byte[] buffer, int offset, int len) throws IOException {
        if(callback != null) {
            callback.execute(new String(buffer, offset, len, charset));
        }
    }

    @Override
    public synchronized void write(int oneByte) throws IOException {
        this.write(new byte[]{(byte) oneByte}, 0, 1);
    }

    @Override
    public void close() throws IOException {
        callback = null;
        super.close();
    }
}
